package com.blic.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.blic.entity.Constant;
import com.blic.entity.UserInfoEntity;
import com.blic.entity.UserInfoEntity.UserStatus;
import com.blic.service.api.IUserInfoService;
import com.blic.utils.OAuthUtil;
import com.blic.utils.URLUtil;

public class WeixinInfoInterceptor  extends HandlerInterceptorAdapter {
	/** 跳转微信验证页 */
	private static final String WEIXIN_AUTH_HTM = "/auth.htm?redirectUrl=";
	private static final String REDIRECT_URL = "RedirectUrl-key";

	/**
	 * 跳转注册页面
	 */
	private static final String REGISTER_HTM = "/userInfo/register.htm";
	private static Logger logger = LoggerFactory.getLogger(WeixinInfoInterceptor.class);

	@Value("${appID}")
	private String appID;

	@Value("${weixinAuthUrl}")
	private String weixinAuthUrl;

	@Value("${baseDaominName}")
	private String baseDaominName;

	@Autowired
	private OAuthUtil oauthUtil;

	@Autowired
	public IUserInfoService userInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		
		String requestType=request.getHeader("x-requested-with"); 
		if(requestType != null){
			return true;
		}
		String uri = request.getRequestURI();
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute(Constant.SESSION_OPENID_KEY);
		logger.debug("***********HandlerInterceptorAdapter *************" + uri);
		if (openId == null) {
			String code = (String) request.getParameter("code");
			String reqFlag = request.getParameter("reqFlag");
			logger.info("openid is null ,code ----{},flag:{}", code, reqFlag);
			if (code == null) {
				if (reqFlag == null) {

					// 还原参数
					uri += "?reqFlag=1";
					
					uri = getUri(request, uri);
					logger.info("openId--{},uri--{}", openId, uri);
					request.getRequestDispatcher(WEIXIN_AUTH_HTM + uri).forward(request, response);
					return false;
				}

			} else {
				// 根据code 获取openid 放入session
				openId = oauthUtil.getOpenId(code);
				if (openId == null) {
					logger.error("不能获取到微信");
				} else {
					session.setAttribute(Constant.SESSION_OPENID_KEY, openId);

				}
			}
		}

		// 已注册用户，写入session，未注册用户，强制注册，并在cookie中记录 原始请求链接
		UserInfoEntity userInfo = null;
		if (openId != null) {
			userInfo = (UserInfoEntity) session.getAttribute(Constant.SESSION_USERINFO_KEY);

			// 缓存为空，重新读取用户信息 未注册或未激活，去注册页面
			if (userInfo == null ) {
				userInfo = userInfoService.queryByOpenId(openId);

				if (userInfo != null &&  UserStatus.ACTIVE.getKey().equals(userInfo.getUserStatus())) {
					session.setAttribute(Constant.SESSION_USERINFO_KEY, userInfo);
				} else {
					if (! uri.contains(REGISTER_HTM)) {
						
						/**
						 * 未注册用户记录访问URL，注册后会跳
						 */
					//	uri = "?notLogin=1"+getUri(request, uri);
					//	CookieUtil.addCookieMaxAgeDay(response, REDIRECT_URL, uri);
						
						logger.info("openId--{},uri--{}", openId, uri);
						request.getRequestDispatcher(REGISTER_HTM).forward(request, response);
						return false;
					}
				}
			}
		}

		return true;
	}

	public String auth(String redirectUrl) {
		StringBuilder url = new StringBuilder();
		url.append(weixinAuthUrl);
		url.append("appid=");
		url.append(appID);
		url.append("&redirect_uri=");
		url.append(URLUtil.encode(baseDaominName + redirectUrl));
		url.append("&response_type=code");
		url.append("&scope=snsapi_base");
		url.append("&state=00#wechat_redirect");
		return url.toString();
	}
	
	private String getUri(HttpServletRequest request,String uri){
		@SuppressWarnings("unchecked")
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			uri += "&" + paraName + "=" + request.getParameter(paraName);
		}
		
		return URLUtil.encode(uri);
	}
}
